package com.fancon.android.gardenjokesx.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.dialog.ProfilePictureSettingDialog;
import com.fancon.android.gardenjokesx.dialog.U08Dialog;
import com.fancon.android.gardenjokesx.dialog.U08_1Dialog;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

public class ProfileSettingActivity extends GardenJokesBaseActivity implements
		OnClickListener {
	private View backBtn, editElement, news, findFriend, editProfile,
			editProfileImage, sharingSetting, aboutApp, emailSupportCenter,
			term, privacypolicy, logout, notification;
	public static String OK = "0";
	private boolean mPrivacy = false;
	private LinearLayout privacySetting;
	private LinearLayout cancelPrivacySetting;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mesx_profile_setting_u02);
		TextView title = (TextView) findViewById(R.id.action_bar_textview_title);
		title.setText(getText(R.string.u02_settings));

		backBtn = findViewById(R.id.action_bar_button_back);
		editProfile = findViewById(R.id.u02_btnEditProfile);
		editProfileImage = findViewById(R.id.u02_btnEditProfileImage);
		sharingSetting = findViewById(R.id.u02_btnSharing);
		aboutApp = findViewById(R.id.u02_btnWebpage);
		emailSupportCenter = findViewById(R.id.u02_btnEmailSupport);
		term = findViewById(R.id.u02_btnTerm);
		privacypolicy = findViewById(R.id.u02_btnPrivacyPolicy);
		logout = findViewById(R.id.u02_btnLogout);
		// privacySetting = findViewById(R.id.u02_tvPrivacySettingOn);
		// cancelPrivacySetting = findViewById(R.id.u02_tvcancelPrivacySetting);
		editElement = findViewById(R.id.u02_btnEditYou);
		findFriend = findViewById(R.id.u02_btnFindFriend);
		notification = findViewById(R.id.u02_btnNotification);
		news = findViewById(R.id.u02_news);
		privacySetting = (LinearLayout) findViewById(R.id.u02_privacySetting);
		privacySetting.setOnClickListener(this);
		cancelPrivacySetting = (LinearLayout) findViewById(R.id.u02_tvcancelPrivacySetting);
		cancelPrivacySetting.setOnClickListener(this);

		backBtn.setOnClickListener(this);
		editProfile.setOnClickListener(this);
		editProfileImage.setOnClickListener(this);
		sharingSetting.setOnClickListener(this);
		aboutApp.setOnClickListener(this);
		emailSupportCenter.setOnClickListener(this);
		term.setOnClickListener(this);
		privacypolicy.setOnClickListener(this);
		logout.setOnClickListener(this);
		// privacySetting.setOnClickListener(this);
		// cancelPrivacySetting.setOnClickListener(this);
		editElement.setOnClickListener(this);
		news.setOnClickListener(this);
		findFriend.setOnClickListener(this);
		notification.setOnClickListener(this);
		SharedPreferences settings = getSharedPreferences(Constant.PREFS_NAME,
				0);
		mPrivacy = settings.getBoolean(Constant.IS_PRIVATE, false);
		// @binhbt
		if (mPrivacy) {
			privacySetting.setVisibility(View.GONE);
			cancelPrivacySetting.setVisibility(View.VISIBLE);
			// mBtnRequest.setVisibility(View.VISIBLE);
		} else {
			privacySetting.setVisibility(View.VISIBLE);
			cancelPrivacySetting.setVisibility(View.GONE);
			// mBtnRequest.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == backBtn) {
			finish();
		} else if (v == editProfile) {
			// Setting user profile
			Intent intent = new Intent(getApplicationContext(),
					EditProfileActivity.class);
			startActivity(intent);
		} else if (v == editProfileImage) {
			// Setting user profile image
			Bundle b = new Bundle();
			b.putInt(Constant.SCREEN_ID, Constant.U02);
			Dialog settingPicture = new ProfilePictureSettingDialog(
					ProfileSettingActivity.this, b);
			settingPicture.show();

		} else if (v == sharingSetting) {
			// Setting sharing setting
			Intent intent = new Intent(this, S03Activity.class);
			startActivity(intent);

		} else if (v == aboutApp) {
			// goto app website
			Intent browserIntent = new Intent(
					Intent.ACTION_VIEW,
					Uri.parse(linkContainHttp(getString(R.string.common_web_app))));
			startActivity(browserIntent);

		} else if (v == emailSupportCenter) {
			// Open email client
			email(this, getString(R.string.common_email_support), "", "");

		} else if (v == term) {
			// Show the term
			Intent intent = new Intent(this, TermActivity.class);
			startActivity(intent);

		} else if (v == privacypolicy) {
			// Show the privacy policy
			Intent intent = new Intent(this, PrivacyPolicyActivity.class);
			startActivity(intent);

		} else if (v == logout) {
			// Logout user
			UserUtil.logoutUser(this);
			LogoutRequest logoutRequest = new LogoutRequest("profilesetting",
					ProfileSettingActivity.this);
			getGlobalState().getRequestQueue().addRequest(logoutRequest);
			Intent intent = new Intent(getApplicationContext(),
					SplashScreenActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			getApplicationContext().startActivity(intent);
			finish();
		} else if (v == privacySetting) {
			// Setting user private or public
			// Open Dialog U08
			Log.d("privacy", "OK");
			U08Dialog u08Dialog = new U08Dialog(ProfileSettingActivity.this);
			u08Dialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface arg0) {
					Log.v("Cate L", "onDismiss");
					if (OK.equals(Constant.PUBLIC)) {
						registerPrivacy(Constant.PUBLIC);
						OK = Constant.NOT_PUBLIC;
					}
				}
			});
			u08Dialog.show();

		} else if (v == cancelPrivacySetting) {
			// Open Dialog U08-1
			Log.d("cancel", "OK");
			U08_1Dialog u08_1Dialog = new U08_1Dialog(
					ProfileSettingActivity.this);

			u08_1Dialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface arg0) {
					Log.v("Cate L", "onDismiss");
					if (OK.equals(Constant.PUBLIC)) {
						registerPrivacy(Constant.NOT_PUBLIC);
						OK = Constant.NOT_PUBLIC;
					}
				}
			});
			u08_1Dialog.show();
		} else if (v == editElement) {
			// Setting user element
			Intent intent = new Intent(this, EditYouElementActivity.class);
			startActivity(intent);

		} else if (v == findFriend) {
			// Find friends
			Intent intent = new Intent(this, S04Activity.class);
			startActivity(intent);

		} else if (v == notification) {
			// Notification setting
			Intent intent = new Intent(this, NotificationSettingActivity.class);
			startActivity(intent);
		} else if (v == news) {
			Intent intent = new Intent(this, U21_22Activity.class);
			startActivity(intent);
		}
	}

	/**
	 * Register privacy
	 * 
	 * @param register
	 * @return
	 */
	public Boolean registerPrivacy(String register) {
		/**
		 * save info if user login
		 */
		UserPrivacyRequest request = new UserPrivacyRequest("u02",
				ProfileSettingActivity.this, register);
		getGlobalState().getRequestQueue().addRequest(request);
		return true;
	}

	// Using thread to download data from server
	class UserPrivacyRequest extends RequestUI {
		private Activity context;
		private FanconProgressBar progress;
		private String registerPrivacy;
		private Boolean isFirst = true;
		private boolean success;

		public UserPrivacyRequest(Object key, Activity activity,
				String registerPrivacy) {
			super(key, activity);
			context = activity;
			this.registerPrivacy = registerPrivacy;
			if (isFirst) {
				progress = FanconProgressBar.show(context,
						context.getString(R.string.common_loading));
			}
		}

		@Override
		public void execute() {
			try {
				// Register privacy
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						2);
				nameValuePairs.add(new BasicNameValuePair("user_id", UserUtil
						.getInfoUserLogin(context).getUser_id()));
				nameValuePairs.add(new BasicNameValuePair("is_privacy",
						registerPrivacy));
				GardenJokesApiConnect api = new GardenJokesApiConnect(context);
				String result = api.execGet(context,
						GardenJokesApiConnect.GROUP_U, "registerPrivacy",
						nameValuePairs);
				Log.v("StringResult", result);
				try {
					JSONObject jObject = new JSONObject(result);
					success = jObject.getBoolean("is_success");
				} catch (JSONException e) {
					// TODO: nothing
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			try {
				if (success) {
					if (registerPrivacy.equals(Constant.PUBLIC)) {
						mPrivacy = true;
					} else {
						mPrivacy = false;
					}
					SharedPreferences settings = getSharedPreferences(
							Constant.PREFS_NAME, 0);
					SharedPreferences.Editor edit = settings.edit();
					if (registerPrivacy.equals(Constant.PUBLIC)) {
						edit.putBoolean(Constant.IS_PRIVATE, true);
					} else {
						edit.putBoolean(Constant.IS_PRIVATE, false);
					}
					edit.commit();
				}
				if (mPrivacy) {
					privacySetting.setVisibility(View.GONE);
					cancelPrivacySetting.setVisibility(View.VISIBLE);
					// mBtnRequest.setVisibility(View.VISIBLE);
				} else {
					privacySetting.setVisibility(View.VISIBLE);
					cancelPrivacySetting.setVisibility(View.GONE);
					// mBtnRequest.setVisibility(View.GONE);
				}
				if (progress != null) {
					progress.dismiss();
				}
				isFirst = false;
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
	}

	/**
	 * Generate standard link to open web Page
	 * 
	 * @param url
	 * @return standard url
	 */
	public String linkContainHttp(String url) {
		String link = "";
		if (url.startsWith("http")) {
			return url;
		} else {
			link = "http://" + url;
		}
		return link;
	}

	/**
	 * Open mail client to send email
	 * 
	 * @param context
	 * @param emailTo
	 * @param subject
	 * @param emailText
	 *            : content of email
	 */
	public void email(Context context, String emailTo, String subject,
			String emailText) {

		Intent i = new Intent(Intent.ACTION_SEND);

		i.setType("message/rfc822"); // use from live device
		i.putExtra(Intent.EXTRA_EMAIL, new String[] { emailTo });
		i.putExtra(Intent.EXTRA_SUBJECT, subject);
		i.putExtra(Intent.EXTRA_TEXT, emailText);
		context.startActivity(i);
	}

	class LogoutRequest extends RequestUI {
		private Activity context;

		public LogoutRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void execute() throws Exception {
			// Log.d("signup", execPost());
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("user_id", UserUtil
					.getInfoUserLogin(context).getUser_id()));
			GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(
					ProfileSettingActivity.this);
			String result = apiConnect.execPost(ProfileSettingActivity.this,
					GardenJokesApiConnect.GROUP_U, "logout", nameValuePairs);
			Log.d("logout", result);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub

		}

	}
}
